#!/bin/bash

echo "🛑 停止 AI Chat 系统"
echo "======================="

# 从PID文件停止服务
stop_service() {
    local service_name=$1
    local pid_file=$2
    
    if [ -f "$pid_file" ]; then
        local pid=$(cat "$pid_file")
        if kill -0 "$pid" 2>/dev/null; then
            echo "🔄 停止 $service_name (PID: $pid)..."
            kill "$pid" 2>/dev/null || true
            sleep 1
            # 如果进程还在运行，强制杀死
            if kill -0 "$pid" 2>/dev/null; then
                echo "   强制停止 $service_name..."
                kill -9 "$pid" 2>/dev/null || true
            fi
            echo "   ✅ $service_name 已停止"
        else
            echo "   ℹ️  $service_name 进程不存在"
        fi
        rm -f "$pid_file"
    else
        echo "   ⚠️  未找到 $service_name 的PID文件"
    fi
}

# 停止各个服务
stop_service "模拟API" "logs/api.pid"
stop_service "后端API" "logs/backend.pid"
stop_service "React前端" "logs/frontend.pid"

echo ""
echo "🧹 清理进程..."

# 按进程名杀死可能遗留的进程
pkill -f "python.*api.py" 2>/dev/null && echo "   清理 api.py 进程" || true
pkill -f "python.*backend.py" 2>/dev/null && echo "   清理 backend.py 进程" || true
pkill -f "npm.*dev" 2>/dev/null && echo "   清理 npm dev 进程" || true

echo ""
echo "🔌 清理端口..."

# 强制释放端口
# 同步 start.sh 的端口配置（前端默认 4000，可通过环境变量 FRONTEND_PORT 覆盖）
FRONTEND_PORT=${FRONTEND_PORT:-4000}
for port in 8000 8100 8200 $FRONTEND_PORT; do
    if lsof -i:$port > /dev/null 2>&1; then
        echo "   清理端口 $port..."
        lsof -ti:$port | xargs kill -9 2>/dev/null || true
    fi
done

echo ""
echo "🔍 检查剩余进程..."
remaining=$(ps aux | grep -E "(api\.py|backend\.py|npm.*dev)" | grep -v grep | wc -l)
if [ "$remaining" -eq 0 ]; then
    echo "   ✅ 所有进程已清理完毕"
else
    echo "   ⚠️  仍有 $remaining 个相关进程在运行"
    ps aux | grep -E "(api\.py|backend\.py|npm.*dev)" | grep -v grep
fi

echo ""
echo "✅ 系统停止完成！"
echo ""
echo "📝 日志文件保留在 logs/ 目录中"
echo "🚀 重新启动: ./start.sh"
